import React, { useState, useEffect } from 'react'
import { SearchBar } from 'antd-mobile'
import { useNavigate, NavLink } from 'react-router-dom'
import './search.scss'
import { IGoods } from '../../interface'
import API from '../api/search'

const tabs = [
    {
      title: '蛋糕',
      key: '1'
    },
    {
      title: '面包',
      key: '2'
    },
    {
      title: '下午茶',
      key: '3'
    },
    {
      title: '冰淇淋',
      key: '4'
    },
  ]
export default function Search() {
    const navigate = useNavigate()
    const [searchList, setSearchList] = useState<IGoods[]>([])
    const [val, setVal] = useState<string>('')
    const searchGoods = async () => {
        let res = await API['searchGoods'](val)
        console.log(res, '搜索')
        setSearchList(res.data.data)
    }
    useEffect(() => {
        searchGoods()
    }, [val])
    const changeVal = (val: string) => {
        setVal(val)
    }
    return (
        <>
            {
                <><div className='search'>
                <SearchBar placeholder='请输入关键词、商品名、分类' showCancelButton={() => true} onCancel={() => navigate(-1)} onChange={changeVal} value={val} />
            </div>
                <div className='search_main'>
                    <h2>为您推荐</h2>
                    <hgroup>
                        {
                            tabs.map((item:any)=><div key={item.key}><NavLink to={'/find'}>{item.title}</NavLink></div>)
                        }
                    </hgroup>
                    <h2>{searchList.length>40?'热门商品':'找到的商品'}</h2>
                    <div className='details'>
                        {
                            searchList.length? searchList.map((ele: IGoods) => <div
                            key={ele._id}
                            id={ele._id}>
                            <NavLink to={'/topic/' + ele._id}><img src={ele.img} alt="" />
                                <h4>{ele.goods_name}</h4>
                                <p>{`${ele.price} / ${ele.weight} 磅`}</p></NavLink>
                        </div>) : <h1>没有该商品噢！</h1>
                        }
                    </div>
                </div></>
            }
        </>

    )
}
